<?php

namespace app\api\controller;

use app\common\BaseHelper;

use app\admin\model\Area;
use app\admin\model\Userproductcard as UserproductcardMdl;
use app\admin\model\Image;
use app\admin\service\Userproductcard as UserproductcardService;

use think\Db;
use think\Exception;
use think\Request;

class Userproductcard extends BaseController
{

    /**
     * 列表
     */
    public function getList()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->uid)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'uid 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        //$userId = $param->userId;
        $where = [
            'userId' => $param->uid
        ];

        $model = new UserproductcardMdl();
        $fields = '*';
        $order = 'createDate DESC';
        $result = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();
        $total = $model->where($where)->count();
        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关数据');
        }

        foreach ($result as $item) {
            $item['cityName'] = Area::where('id', $item['cityId'])->value('name');
            $item['xianName'] = Area::where('id', $item['xianId'])->value('name');
            $item['townName'] = Area::where('id', $item['townId'])->value('name');
            $item['villageName'] = \app\admin\model\Villages::where('id', $item['villageId'])->value('name');
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 详情
     */
    public function getDetail()
    {
        $param = self::getHttpParam();

        if (empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'id 不能为空');
        }

        $where = [
            'id' => $param->id
        ];
        $model = new UserproductcardMdl();
        $field = '*';
        $item = $model->where($where)->field($field)->find();
        if (!$item) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到相关数据');
        }

        // 用户头像
        $userInfo = \app\admin\model\User::where('id', $item['userId'])->field('avatarUrl, memberId')->find();
        $userAvatar = $userInfo['avatarUrl'];
        if($userInfo['memberId']){
            $userAvatar = \app\admin\model\Member::where('id', $userInfo['memberId'])->value('avatar');
        }
        $item['userAvatar'] = $userAvatar;
        $item['cityName'] = Area::where('id', $item['cityId'])->value('name');
        $item['xianName'] = Area::where('id', $item['xianId'])->value('name');
        $item['townName'] = Area::where('id', $item['townId'])->value('name');
        $item['villageName'] = \app\admin\model\Villages::where('id', $item['villageId'])->value('name');
        // 二维码
        if($item['qrcode']){
            $item['qrcode'] = 'https://' . $_SERVER['SERVER_NAME'] . '/public/upload/' . $item['qrcode'];
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 保存
     */
    public function save()
    {
        $param = self::getHttpParam();

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->contactName)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '联系人(contactName) 不能为空');
        }
        if (empty($param->mobile)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '手机号(mobile) 不能为空');
        }
        if (empty($param->varietieId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '产品品种(varietieId) 不能为空');
        }
        if (empty($param->productspec)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '产品规格(productspec) 不能为空');
        }
        if (empty($param->villageId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '产地(villageId) 不能为空');
        }
        if (empty($param->address)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '详细地址(address) 不能为空');
        }
        if (empty($param->quantity)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '供货量(quantity) 不能为空');
        }
        if(empty($param->priceType)){
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'priceType 不能为空');
        }
        if($param->priceType == 1) {
            if (empty($param->landPrice)) {
                return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '地头价(landPrice) 不能为空');
            }
        } else if($param->priceType == 2){
            if (empty($param->aboardPrice)) {
                return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '上车价(aboardPrice) 不能为空');
            }
        }
        if(empty($param->unit)){
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '单位(unit) 不能为空');
        }
        if (empty($param->slogan)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '宣传语(slogan) 不能为空');
        }

        $userId = $param->userId;

        Db::startTrans();
        try {
            $data = (array)$param;
            $model = new UserproductcardMdl();

            $xianId = Area::where('id', $param->townId)->value('parentId');
            $cityId = Area::where('id', $xianId)->value('parentId');
            $data['cityId'] = $cityId;
            $data['xianId'] = $xianId;

            if (!empty($param->id)) {
                $id = $param->id;
                $data['updateDate'] = time();
                $data['userId'] = $userId;

                $result = $model->allowField(true)->save($data, ['id' => $id]);
            } else {
                $data['id'] = BaseHelper::getUUID();
                $data['createDate'] = time();

                // 生成二维码
                $data['qrcode'] = UserproductcardService::createQrCode($data['id'], $data['townId']);
                if(!$data['qrcode']){
                    //return show(config('status.ERROR_STATUS'), self::NOT_DATA, '生成二维码失败！');
                }

                $result = $model->save($data);
            }

            if($result !== false){
                /*
                // 图片
                $res = '';
                if(isset($param->imgIds) && $param->imgIds) {
                    $imgIds = (array) $param->imgIds;
                    foreach($imgIds as $key => $imgId){
                        $res = Image::where(['id' => $imgId])->update(['relatedId' => $data['id'], 'relatedTable' => 'userproductcard', 'tag' => 'imglist', 'sorting' => $key]);
                    }
                }
                if($res === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::NOT_DATA, '保存图片失败');
                }
                */
                Db::commit();
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'), '保存失败', $model->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), '保存失败', $e->getMessage());
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 删除
     */
    public function delete()
    {
        $param = self::getHttpParam();

        if (empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'id 不能为空');
        }

        $where = [
            'id' => $param->id
        ];
        $model = new UserproductcardMdl();
        $result = $model->where($where)->delete();
        if ($result === false) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '删除失败');
        }

        // Query执行后的操作
        $model->_after_delete($param->id);

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
    }
}